package com.data;

import java.io.ByteArrayInputStream;
import java.io.StreamCorruptedException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

import com.constant.Constant;
import com.net.ClientError;
import com.net.ClientException;
import com.net.RequestParameter;
/**
 * 续借图书接口
 * 请求参数：
 * <bar_code>:图书编号
 * <check>:在图书列表中返回
 * <cookie> : cookie，在登陆之后后返回
 * @author lenovo
 * 
 * 续借失败时返回数据格式如下：
 * <font color=red>不到续借时间，不得续借</font>
 * 
 * 续借成功时的数据格式
 * <font color=green>续借成功</font>
 *
 */
public final class RenewBookData extends BaseData {

	private final static String TAG = "renew_book";
	
	private boolean bSuccess = false;
	
	@Override
	public void startParse(RequestParameter parameter) throws Exception,
			ClientException {
		
		String bar_code = parameter.getValue("bar_code");//图书编号
		if(bar_code == null)
			throw new NullPointerException("bar_code值为null");
		String check = parameter.getValue("check");
		if(check == null)
			throw new NullPointerException("check值为null");
		String cookie = parameter.getValue("cookie");
		if(cookie == null)
			throw new NullPointerException("cookie为null");
		
		String url = "http://202.115.151.118:8080/reader/ajax_renew.php?bar_code=" + bar_code + 
				"&check=" + check + "&time=" + new Date().getTime();
		
		openConnection(url, cookie);
	}
	
	protected void openConnection(final String urls, final String cookie) throws Exception{
		URL url = new URL(urls);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		
		connection.setDoOutput(true);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Accept", "Accept	text/html, */*; q=0.01");
		connection.setRequestProperty("Referer", "http://202.115.151.118:8080/reader/book_lst.php");
		connection.setRequestProperty("Host", "202.115.151.118:8080");
		connection.setRequestProperty("Cookie", cookie);
		connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(false);
		
		connection.connect();
		if(connection.getResponseCode() != 200) {
			Log.e(TAG, "数据获取失败!");
			throw new ClientException("网络请求失败", ClientError.ERROR_CONNECTION);
		}
		
		
		// 不到续借时间，不得续借！
		String stream = getWebSource(connection.getInputStream(), "utf-8");
		if(stream.contains("不到续借时间，不得续借！")) {
			bSuccess = false;
		} else if(stream.contains("续借成功")) {
			bSuccess = true;
		}
		
	} // openConnection
	
	/**
	 * 成功返回true，失败返回false
	 * @return
	 */
	public boolean getStatus() {
		return bSuccess;
	}

}
